<?php

namespace System\Controllers;

if (!defined('BASEPATH')) die('Access Denied.');

use \System\Models\DBText as DBText;

/**
 * Access Class
 * 
 * Handles confirmation e-mails and the password recover system.
 */
class Access extends \System\Core\Controller
{

    private $data = array();
    
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->library('validation');
        $this->load->model('dbtext');
    }

    public function indexAction()
    {
        show_404('access');
    }

    /**
     * Presents the revover form.
     */
    public function recoverAction()
    {
        $this->view->templateRender('outside', 'access/recover', 'Recover', $this->data);
    }
    
    /**
     * Handles the post information from the recover form.
     */
    public function submitrecoverAction()
    {
        if ($this->input->isPost())
        {
            $this->validation->addRule('email', 'e-mail', 'trim|email|maxlen=100');
            if ($this->validation->run())
            {
                $this->db->where('email', $this->input->post('email'));
                $this->db->get('users');
                if ($this->db->num_rows() == 1)
                {
                    $row = $this->db->row();
                    $convert = array(
                        'name' => $row->name,
                        'email' => $row->email,
                        'ip' => $this->input->GetIpAddr(),
                        'url' => baseUrl().'access/recover_info/id/'.$row->id.'/code/'.$row->salt
                    );
                    
                    $message = $this->dbtext->getText(DBText::EMAILRECOV, $convert);
                    
                    if (@mail($row->email, 'Recover Account'.$this->config->getItem('site_name'), $message, "From: {$this->config->getItem('site_email')}"))
                    {   
                        $this->fc->infoMsg('A mail has been sent to {$row->email} with further information how to recover your account.');
                    }
                    else
                    {
                        $this->fc->errorMsg('An error occurred while trying to send the email.');
                    }
                }
                else
                {
                    $this->data['errors'][] = 'The e-mail address you entered is not in the database.';
                    $this->recoverAction();
                }
            }
            else
            {
                $this->data['errors'] = $this->validation->getErrors();
                $this->recoverAction();
            }
        }
        else
        {
            $this->fc->warningMsg('Attempts to hack the recover system might lead to an IP ban.');
        }
    }
       
    /**
     * Handles the confirmation e-mail letter.
     */
    public function confirmAction()
    {
        $id = $this->input->param('id');
        $code = $this->input->param('code');
        if ($id != FALSE && $code != FALSE)
        {
            $this->db->where('id', $id);
            $this->db->where('salt', $code);
            $this->db->where('confirmed', 0);
            $this->db->get('users');
            if ($this->db->num_rows() == 1)
            {
                $this->db->update('users', array('confirmed' => 1), array('passkey' => $code));
                $this->fc->message('You have been confirmed!', 'You have been confirmed and can now log in to the site by going to the '.anchor('login', 'login').' page.');
            }
            else
            {
                $this->fc->errorMsg('The confirmation code is not valid.');
            }
        }
        else
        {
            $this->fc->warningMsg('Attempts to hack the confirmation system might lead to an IP ban.');
        }        
    }
    
    /**
     * The final recover e-mail that returns the new password to the users e-mail.
     */
    public function recover_infoAction()
    {
        $id = $this->input->param('id');
        $code = $this->input->param('code');

        if ($code != FALSE)
        {
            $this->db->where('id', $id);
            $this->db->where('salt', $code);
            $this->db->where('confirmed', 1);
            $this->db->get('users');
            if ($this->db->num_rows() == 1)
            {
                $row = $this->db->row();
                // Create a new password.
                $newPassword = createPassword();
                $hash = createPasswordHash($row->salt, $newPassword);

                $this->db->update('users', array('password' => $hash), array('id' => $id));

                $convert = array(
                    'NAME' => $row->name,
                    'PASSWORD' => $newPassword,
                    'URL' => baseUrl().'login'
                );
                $message = $this->dbtext->getText(DBText::EMAILACCOUNT, $convert);

                if (@mail($row->email, 'Account Information', $message, "From: {$this->config->getItem('site_email')}"))
                {      
                    $this->fc->message('Mail Sent', 'An e-mail has been sent to {$row->email} with your new password.');
                }
                else
                {
                    $this->fc->errorMsg('An error occurred while trying to send the email.');
                }
                 
            }
            else
            {
                $this->fc->errorMsg('The recover code is not valid.');
            }
        }
        else
        {
            $this->fc->warningMsg('Attempts to hack the recovery system might lead to an IP ban.');
        }
    }
    
}

?>
